package com.ischoolbar.programmer.interceptor.admin;

import com.google.gson.JsonObject;
import com.ischoolbar.programmer.entity.admin.Menu;
import com.ischoolbar.programmer.utils.MenuUtil;
import com.sun.activation.registries.MailcapParseException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Object admin = request.getSession().getAttribute("admin");



        if (admin == null) {
            String header = request.getHeader("X-Requested-With");
            if ("XMLHttpRequest".equals(header)) {
                Map<String, String> ret = new HashMap<>();
                ret.put("type", "error");
                ret.put("msg", "登录会话超时, 请重新登录");
                response.getWriter().write(JSONObject.fromObject(ret).toString());
            }

            response.sendRedirect(request.getServletContext().getContextPath() + "/system/login");
            return false;
        }

        String mid = request.getParameter("_mid");
        if (!StringUtils.isEmpty(mid)) {
            List<Menu> thirdList = MenuUtil.findAllThirdList((List<Menu>)request.getSession().getAttribute("menuList"), Integer.valueOf(mid));
            request.setAttribute("thirdList", thirdList);
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
